﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using Microsoft.MediaCenter.UI;
using Microsoft.MediaCenter.Hosting;
using System.Threading;
using System.IO;
using Microsoft.Search.Interop;
using System.Data.OleDb;
using Level65.WMVHelper;
using Level65.ClipShow;

namespace ClipShow
{
    public class StartupCodeBehind 
    {
        public StartupCodeBehind()
        {
        }

        private void CrawlTarget(string targetDir)
        {
            Reader wmvReader = new Reader();

            // Look for shortcuts from Public\Videos
            foreach (string file in Directory.GetFiles(targetDir, "*.lnk"))
            {
                ArrayList results2 = new ArrayList();
                ClipShowContent csc = new ClipShowContent();

                try
                {
                    string shortCut = wmvReader.GetShortCut(file);
                    csc.ContentSourceName = Path.GetFileNameWithoutExtension(file);
                    csc.WatchFolders = false;
                    results2.AddRange(wmvReader.CrawlDirectory(csc.ContentSourceName, shortCut, true));
                    if (results2.Count > 0)
                    {
                        csc.MediaItems.AddRange(results2);
                        wmvReader.PersistThumbnailWork();
                        BuildTopicsAndPersist(csc);
                    }
                }
                catch (ArgumentNullException)
                {
                }
                catch (SystemException)
                {
                    //TODO:  Log this exception?
                }
            }
        }

        private static OleDbConnection _connection;    
        private static OleDbDataReader ExecuteReader(string query)
        {
            string connectionString = "Provider=Search.CollatorDSO;Extended Properties='Application=Windows';";
            _connection = new OleDbConnection(connectionString);
            _connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = _connection;
            command.CommandText = query;
            OleDbDataReader reader = command.ExecuteReader();
            return reader;
        }
        public void SearchLocal(string contentSourceName, string[] fileTypes)
        {
            try
            {
                ClipShowContent rootCm = new ClipShowContent();
                Reader localReader = new Reader();

                try
                {
                    // First use Windows Search to find our local media
                    CSearchManager manager = new CSearchManagerClass();
                    CSearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");
                    CSearchQueryHelper queryHelper = catalogManager.GetQueryHelper();
                    rootCm.ContentSourceName = contentSourceName;
                    foreach (string fileType in fileTypes)
                    {
                        string query = "";
                        queryHelper.QuerySelectColumns = "\"System.ItemUrl\"";
                        if ( (fileType.Equals("*.dvr-ms")) || (fileType.Equals("*.wtv")))
                        {
                            query = queryHelper.GenerateSQLFromUserQuery(String.Format("* kind:tv ext:{0} store:file", fileType));
                        }
                        else
                        {
                            query = queryHelper.GenerateSQLFromUserQuery(String.Format("* kind:videos ext:{0} store:file", fileType));
                        }
                        OleDbDataReader reader = ExecuteReader(query);
                        while (reader.Read())
                        {
                            Uri convert = new Uri(reader.GetString(0));
                            rootCm.MediaItems.Add(localReader.GetInfo(convert.LocalPath));
                        }
                        reader.Close();
                    }
                }
                catch 
                {
                    // Future:  Work on handling an exception
                }
                finally
                {
                    // Persist the files we have so far
                    BuildTopicsAndPersist(rootCm);
                    localReader.PersistThumbnailWork();
                }
            }
            catch
            {

            }
         }

        public void CrawlLinkedShares()
        {
            Storage st = new Storage();

            //ClipShowContent csc = st.GetMediaLibrary(@"C:\ProgramData\clipShow Settings\MediaSources\my test.xml");

            //BuildTopicsAndPersist(csc);


            // Now search folders for shortcuts
            // Search in C:\Users\username\Videos and C:\Users\Public\Videos
            string myFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            string publicFolder = String.Format("{0}Users\\Public\\Videos", Path.GetPathRoot(myFolder));
            myFolder = myFolder.Replace("Pictures", "Videos");

            if (Directory.Exists(myFolder))
            {
                CrawlTarget(myFolder);
            }
            if (Directory.Exists(publicFolder))
            {
                CrawlTarget(publicFolder);
            }

            Reader wmvReader = new Reader();
            bool persistThumbwork = false;

            // Check for existing playlists thumbs
            ArrayList myPlaylists = st.GetMyCollections();
            if (myPlaylists.Count > 0)
            {
                foreach (ClipCollection mc in myPlaylists)
                {
                    ClipItem ci = (ClipItem)mc.Items[0];
                    foreach (MediaMetaData med in ci.MediaItems)
                    {
                        if (!File.Exists(med.ThumbnailUrl))
                        {
                            wmvReader.AddThumbNailJob(med.Url, med.ThumbnailUrl, med.Title);
                            persistThumbwork = true;
                        }
                    }
                }
                if (persistThumbwork)
                {
                    wmvReader.PersistThumbnailWork();
                }

                persistThumbwork = false;
            }

            // Check for existing snags thumbs
            ClipShowContent snags = st.GetSnagCollection();
            ArrayList toRemove = new ArrayList();
            if (snags.MediaItems.Count > 0)
            {
                foreach (MediaMetaData snagItem in snags.MediaItems)
                {
                    if (File.Exists(snagItem.Url))
                    {
                        foreach (SnagItem si in snagItem.SnagList)
                        {
                            if (!File.Exists(si.ThumbnailUrl))
                            {
                                persistThumbwork = true;
                                wmvReader.AddThumbNailJob(snagItem.Url, si);
                            }
                        }
                    }
                    else
                    {
                        toRemove.Add(snagItem);
                    }
                }

                if (persistThumbwork)
                {
                    wmvReader.PersistThumbnailWork();       //Save thumbnail work for background thread
                }
                foreach (MediaMetaData removeItem in toRemove)
                {
                    snags.MediaItems.Remove(removeItem);
                }

                st.PersistSnagCollection(snags);
            }

        }
        static void BuildTopicsAndPersist(ClipShowContent source)
        {
            Storage st = new Storage();
            Topics myTopics = new Topics();

            ArrayList channelTopics = myTopics.BuildTopics(source);
            int maxTopics = channelTopics.Count - Convert.ToInt32((channelTopics.Count * 0.15));

            ClipItem defaultCI = new ClipItem();
            defaultCI.Count = source.MediaItems.Count;
            defaultCI.Keywords = "ALL";
            defaultCI.Name = "All Media";
            MediaMetaData wmd = (MediaMetaData)source.MediaItems[0];
            defaultCI.ThumbnailUrl = wmd.ThumbnailUrl;
            source.KeywordItems.Add(defaultCI);

            int Ctr = channelTopics.Count;
            if (Ctr > 0)
            {
                foreach (ClipTopic ciTopic in channelTopics)
                {
                    source.KeywordItems.Add(BuildChannel(ciTopic.Topic,
                        ciTopic.Keywords,
                        ciTopic.MediaCount, ciTopic.ThumbnailSample));
                    // Bail when we get under our max topics
                    if (Ctr < (channelTopics.Count - maxTopics))
                    {
                        break;
                    }
                    Ctr--;
                }
            }

            st.PersistMediaLibrary(source);
        }
        static ClipItem BuildChannel(string channelName, string keywords, long videoCount, string thumbNail)
        {
            ClipItem ci = new ClipItem();
            ci.Name = channelName;
            ci.Keywords = keywords;
            ci.Count = videoCount;
            ci.ThumbnailUrl = thumbNail;

            return (ci);
        }
    }
}
